#include <cstdio>
#include <cstring>
#include <cerrno>
#include <unistd.h>

#include "netperf_socket.h"

CNetperfSocket::CNetperfSocket(const sockaddr_in& refAddr):
    m_stAddr(refAddr)
{

}

CNetperfSocket::~CNetperfSocket()
{
    
}

int32_t CNetperfSocket::CreateTcpServer()
{
    int iSockFd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (iSockFd == -1)
    {
        printf("socket error, %s\n", strerror(errno));
        return -1;
    }

    int iErr = bind(iSockFd, (const struct sockaddr*)&m_stAddr, sizeof(m_stAddr));
    if (iErr == -1)
    {
        close(iSockFd);
        return -1;
    }

    iErr = listen(iSockFd, 1024);
    if (iErr == -1)
    {
        close(iSockFd);
        return -1;
    }

    return iSockFd;
}

int32_t CNetperfSocket::CreateUdpServer()
{
    int iSockFd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (iSockFd == -1)
    {
        printf("socket error, %s\n", strerror(errno));
        return -1;
    }

    int iErr = bind(iSockFd, (const struct sockaddr*)&m_stAddr, sizeof(m_stAddr));
    if (iSockFd == -1)
    {
        printf("bind error, %s\n", strerror(errno));
        close(iSockFd);
        return -1;
    }

    return iSockFd;
}

int32_t CNetperfSocket::CreateTcpClient()
{
    int iSockFd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (iSockFd == -1)
    {
        printf("socket error, %s\n", strerror(errno));
        return -1;
    }

    int iErr = connect(iSockFd, (const sockaddr*) &m_stAddr, sizeof(m_stAddr));
    if (iErr == -1)
    {
        close(iSockFd);
        return -1;
    }

    return iSockFd;
}

int32_t CNetperfSocket::CreateUdpClient()
{
    int iSockFd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (iSockFd == -1)
    {
        printf("socket error, %s\n", strerror(errno));
        return -1;
    }

    return iSockFd;
}

ssize_t CNetperfSocket::Send(const void* pData, size_t ulDataLen)
{
    return sendto(m_iSockFd, pData, ulDataLen, 0, (const sockaddr*)&m_stAddr, sizeof(m_stAddr));
}

ssize_t CNetperfSocket::Recv()
{
}